package ikar.nrd.fillingref.generator;

import java.util.ArrayList;
import java.util.List;

public abstract class CoreScriptGenerator extends DataBaseManager {

	public static final String XSD_PATH = "resources/fpml/";
	public static final String XML_PATH = "resources/xml/";

	protected List<String> generatedPlateCodesList = new ArrayList<String>();


	protected String shavePlateCodes(String plateCode) {
		boolean vowelShaved = false;
		if (plateCode.contains("TABLE_")) {
			plateCode = plateCode.replace("TABLE_", "");
		}
		while (plateCode.length() >= 90) {
			if (!vowelShaved) {
				plateCode = plateCode.replaceAll("[aeiouAEIOU]", "");
				vowelShaved = true;
			} else {
				plateCode = plateCode.substring(plateCode.split("_")[0].length() + 1, plateCode.length());
			}
		}
		return plateCode;

	}

	public CoreScriptGenerator(String patternId) {
		super(patternId);
	}

	protected String createInsertQuery(String elementName, String parentPlateCode, String newPlateCode, boolean isAttribute, boolean useValue) {
		if (isAttribute) {
			elementName = "@" + elementName;
		}
		if (useValue) {
			elementName += "/value";
		}
		String query = "INSERT INTO " + TEMP_TABLES_NAME + "(PATTERN_ID,PARENT_FIELD_ID,PARENT_PLATE_CODE,XPATH,PLATE_CODE)";
		query += " values(" + getPatternId() + ",NULL,'" + parentPlateCode + "','./" + elementName + "','" + newPlateCode + "') \n";

		return query;

	}

	protected String getNewPlateCode(String elementName, String parentPlateCode) {

		String newPlateCode = PLATE_CODE_INDEX + parentPlateCode + "_" + elementName.toUpperCase();
		Integer plateCodeIndex = 0;
		while (generatedPlateCodesList.contains(newPlateCode)) {
			newPlateCode += (plateCodeIndex++).toString();
		}
		return newPlateCode;
	}

	public String getClearValue(String value) {
		if (value != null) {
			if (value.contains(":")) {
				return value.substring(value.indexOf(":") + 1, value.length());
			}
		}
		return value;
	}

}
